/*
 * @Author: 抱着羊啃 1437670973@qq.com
 * @Date: 2025-10-21 13:53:20
 * @LastEditors: 抱着羊啃 1437670973@qq.com
 * @LastEditTime: 2025-10-27 22:55:36
 * @FilePath: \fall-guard-band\src\main\java\com\example\fall_guard_band\service\ServiceImpl\UserServiceImpl.java
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package com.example.fall_guard_band.service.ServiceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.fall_guard_band.mapper.NursingHomeMapper;
import com.example.fall_guard_band.mapper.UserMapper;
import com.example.fall_guard_band.pojo.entity.NursingHome;
import com.example.fall_guard_band.pojo.entity.User;
import com.example.fall_guard_band.pojo.dto.CreateUserRequest;
import com.example.fall_guard_band.pojo.dto.UpdateUserRequest;
import com.example.fall_guard_band.pojo.dto.UserManagementDTO;
import com.example.fall_guard_band.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final NursingHomeMapper nursingHomeMapper;

    @Override
    public User login(String username, String password, Long nursingHomeId) {
        if (username == null || username.isBlank() || password == null || password.isBlank() || nursingHomeId == null) {
            return null;
        }
        // 验证选择的养老院有效
        NursingHome home = nursingHomeMapper.selectById(nursingHomeId);
        if (home == null || home.getStatus() == null || home.getStatus() != 1) {
            return null;
        }
        // 按多租户过滤用户：用户名 + 状态启用 + 所属养老院匹配
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getStatus, 1)
                .eq(User::getNursingHomeId, nursingHomeId)
                .eq(User::getIsDeleted, 0));
        if (user == null) {
            return null;
        }
        // TODO: 密码应使用加密校验（如BCrypt），当前为明文匹配占位
        if (!password.equals(user.getPassword())) {
            return null;
        }
        return user;
    }

    @Override
    public boolean register(String username, String password, Long nursingHomeId) {
        if (username == null || username.isBlank() || password == null || password.isBlank() || nursingHomeId == null) {
            return false;
        }
        // 验证选择的养老院有效
        NursingHome home = nursingHomeMapper.selectById(nursingHomeId);
        if (home == null || home.getStatus() == null || home.getStatus() != 1) {
            return false;
        }
        // 检查用户名在该养老院下是否已存在
        User exists = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getNursingHomeId, nursingHomeId)
                .eq(User::getIsDeleted, 0));
        if (exists != null) {
            return false;
        }
        // 创建用户并插入
        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 后续可改为加密存储
        user.setStatus(1);
        user.setNursingHomeId(nursingHomeId);
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        int inserted = userMapper.insert(user);
        return inserted == 1;
    }

    @Override
    public boolean resetPassword(String username, String email, String newPassword) {
        if (username == null || username.trim().isEmpty() || email == null || email.trim().isEmpty() || newPassword == null || newPassword.trim().isEmpty()) {
            return false;
        }
        // 根据用户名+邮箱匹配用户，不匹配则重置失败
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getEmail, email)
                .eq(User::getIsDeleted, 0));
        if (user == null) {
            return false;
        }
        user.setPassword(newPassword);
        user.setUpdatedAt(LocalDateTime.now());
        return userMapper.updateById(user) == 1;
    }

    // ============== 用户管理 CRUD ==============
    @Override
    public List<UserManagementDTO> listUsers(Long nursingHomeId, Integer isDeleted) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getIsDeleted, isDeleted == null ? 0 : isDeleted);
        if (nursingHomeId != null) {
            wrapper.eq(User::getNursingHomeId, nursingHomeId);
        }
        List<User> users = userMapper.selectList(wrapper);
        // 批量查询养老院名称，减少 N+1 查询
        Set<Long> homeIds = users.stream()
                .map(User::getNursingHomeId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, String> homeNameMap = homeIds.isEmpty() ? Map.of() :
                nursingHomeMapper.selectList(new LambdaQueryWrapper<NursingHome>().in(NursingHome::getId, homeIds))
                        .stream()
                        .collect(Collectors.toMap(NursingHome::getId, NursingHome::getName));

        List<UserManagementDTO> list = new ArrayList<>();
        for (User u : users) {
            String homeName = u.getNursingHomeId() == null ? null : homeNameMap.get(u.getNursingHomeId());
            list.add(toManagementDTO(u, homeName));
        }
        return list;
    }

    @Override
    public boolean createUser(CreateUserRequest req) {
        if (req == null || isBlank(req.getUsername()) || isBlank(req.getPassword()) || req.getNursingHomeId() == null) {
            return false;
        }
        NursingHome home = nursingHomeMapper.selectById(req.getNursingHomeId());
        if (home == null || !Objects.equals(home.getStatus(), 1)) {
            return false;
        }

        // 用户名在该养老院下唯一，且不允许与未逻辑删除用户重复
        User exists = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, req.getUsername())
                .eq(User::getNursingHomeId, req.getNursingHomeId())
                .eq(User::getIsDeleted, 0));
        if (exists != null) {
            return false;
        }

        User u = new User();
        u.setUsername(req.getUsername());
        u.setPassword(req.getPassword()); // 可后续替换为加密存储
        u.setNursingHomeId(req.getNursingHomeId());
        u.setEmail(req.getEmail());
        u.setRealName(req.getRealName());
        u.setIdCard(req.getIdCard());
        u.setPhone(req.getPhone());
        u.setStatus(req.getStatus() == null ? 1 : req.getStatus());
        u.setCreatedAt(LocalDateTime.now());
        u.setUpdatedAt(LocalDateTime.now());
        return userMapper.insert(u) == 1;
    }

    @Override
    public boolean updateUser(Long id, UpdateUserRequest req) {
        if (id == null || req == null) {
            return false;
        }

        User user = userMapper.selectById(id);
        if (user == null || Objects.equals(user.getIsDeleted(), 1)) {
            return false;
        }

        // 目标养老院ID：若未提供则沿用当前值
        Long targetHomeId = req.getNursingHomeId() != null ? req.getNursingHomeId() : user.getNursingHomeId();
        if (targetHomeId != null) {
            NursingHome home = nursingHomeMapper.selectById(targetHomeId);
            if (home == null || !Objects.equals(home.getStatus(), 1)) {
                return false;
            }
        }

        // 目标用户名：若未提供则沿用当前值；校验在同养老院下唯一（排除自身，且仅针对未逻辑删除用户）
        String targetUsername = req.getUsername() != null ? req.getUsername() : user.getUsername();
        if (!isBlank(targetUsername) && targetHomeId != null) {
            User conflict = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, targetUsername)
                    .eq(User::getNursingHomeId, targetHomeId)
                    .eq(User::getIsDeleted, 0)
                    .ne(User::getId, id));
            if (conflict != null) {
                return false;
            }
        }

        // 按需更新字段（只更新非空）
        if (req.getUsername() != null) user.setUsername(req.getUsername());
        if (req.getPassword() != null) user.setPassword(req.getPassword());
        if (req.getNursingHomeId() != null) user.setNursingHomeId(req.getNursingHomeId());
        if (req.getEmail() != null) user.setEmail(req.getEmail());
        if (req.getRealName() != null) user.setRealName(req.getRealName());
        if (req.getIdCard() != null) user.setIdCard(req.getIdCard());
        if (req.getPhone() != null) user.setPhone(req.getPhone());
        if (req.getStatus() != null) user.setStatus(req.getStatus());

        user.setUpdatedAt(LocalDateTime.now());
        return userMapper.updateById(user) == 1;
    }

    @Override
    public boolean deleteUser(Long id) {
        if (id == null) {
            return false;
        }
        User user = userMapper.selectById(id);
        if (user == null) {
            return false;
        }
        if (Objects.equals(user.getIsDeleted(), 1)) {
            // 幂等：已删除视为成功
            return true;
        }
        LocalDateTime now = LocalDateTime.now();
        LambdaUpdateWrapper<User> uw = new LambdaUpdateWrapper<User>()
                .eq(User::getId, id)
                .set(User::getIsDeleted, 1)
                .set(User::getDeletedAt, now)
                .set(User::getUpdatedAt, now);
        return userMapper.update(null, uw) == 1;
    }

    @Override
    public boolean resetUserPassword(Long id, String newPassword) {
        if (id == null || isBlank(newPassword)) {
            return false;
        }
        User user = userMapper.selectById(id);
        if (user == null || Objects.equals(user.getIsDeleted(), 1)) {
            return false;
        }
        // TODO: 后续可改为加密存储（如BCrypt），当前为明文占位
        LocalDateTime now = LocalDateTime.now();
        LambdaUpdateWrapper<User> uw = new LambdaUpdateWrapper<User>()
                .eq(User::getId, id)
                .set(User::getPassword, newPassword)
                .set(User::getUpdatedAt, now);
        return userMapper.update(null, uw) == 1;
    }



    private boolean isBlank(String s) {
        return s == null || s.trim().isEmpty();
    }

    private UserManagementDTO toManagementDTO(User u, String nursingHomeName) {
        return UserManagementDTO.builder()
                .id(u.getId())
                .username(u.getUsername())
                .realName(u.getRealName())
                .idCard(u.getIdCard())
                .phone(u.getPhone())
                .email(u.getEmail())
                .status(u.getStatus())
                .nursingHomeName(nursingHomeName)
                .isDeleted(u.getIsDeleted())
                .build();
    }
}
